package com.atguigu.crowd.service.impl;

import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.po.MemberPO;
import com.atguigu.crowd.entity.po.MemberPOExample;
import com.atguigu.crowd.exception.LoginFailedException;
import com.atguigu.crowd.mapper.MemberPOMapper;
import com.atguigu.crowd.service.api.MemberService;
import com.atguigu.crowd.util.CrowdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author cyb315
 * @create 2021-11-06 10:55
 */
// 在类上使用@Transactional(readOnly = true)针对查询操作设置事务属性
@Transactional(readOnly = true)
@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberPOMapper memberPOMapper;


    /**
     * 根据账号loginacct返回member对象信息的业务实现方法
     *
     * @param loginacct 会员账号
     * @return
     */
    @Override
    public MemberPO getMemberPOByLoginAcct(String loginacct) {

        // 1.根据表单的登录账号查询MemberPO对象
        // 1.1封装查询条件
        MemberPOExample example = new MemberPOExample();
        MemberPOExample.Criteria criteria = example.createCriteria();
        criteria.andLoginacctEqualTo(loginacct);
        // 1.2执行查询
        List<MemberPO> memberPOList = memberPOMapper.selectByExample(example);

        // 2.特殊情况抛出异常
        // 2.1判断结果集合对象是否为null
        if (memberPOList == null || memberPOList.size() == 0) {
            // 如果为空则抛出异常LoginFailedException
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        // 2.2如果查询出多个MemberPO对象可能是测试数据等导致，以防万一也抛出异常
        if (memberPOList.size() > 1) {
            throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }
        // 2.3从查询结果中获取封装的MemberPO对象
        MemberPO memberPO = memberPOList.get(0);
        // 如果查询到的MemberPO对象为空则抛出异常
        if (memberPO == null) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 3.无异常获取结果
        return memberPO;

    }

    /**
     * 保存Member对象的业务实现方法
     *
     * @param memberPO
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public void saveMember(MemberPO memberPO) {
        memberPOMapper.insertSelective(memberPO);
    }
}
